$(function() {
    var taskTable1 = null;
    var taskTable2 = null;
    var mainCtrl = avalon.define({
        $id: "mainController",
        taskTopic: "",
        startTime: "",
        endTime: "",
        categoryList: [],
        isSave: false,
        taskNo: "",
        categoryNameTxt: "",
        isimppercent: false,
        isimpcomm: false,
        tabIdx: 0,
        selTab: function() {
            mainCtrl.tabIdx = $(this).index();
        },
        saveTask: function() {
            $(this).next(".err-box").hide();
            if (mainCtrl.taskTopic == "") {
                $(this).next(".err-box").show().find(".u-error").text("任务主题不能为空");
                return;
            }
            if (mainCtrl.endTime == "" || mainCtrl.startTime == "") {
                $(this).next(".err-box").show().find(".u-error").text("任务时间不能为空");
                return;
            }
            var categoryName = $(".cnt-box select option:selected").text();
            var categoryCode = $(".cnt-box select option:selected").val();
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "categoryCode": categoryCode,
                    "categoryName": categoryName,
                    "endTime": mainCtrl.endTime,
                    "startTime": mainCtrl.startTime,
                    "taskTopic": mainCtrl.taskTopic
                },
                url: DI.addTask,
                success: function(data) {
                    if (data.retFlag == 1) {
                        mainCtrl.isSave = true;
                        mainCtrl.categoryNameTxt = categoryName;
                        mainCtrl.taskNo = data.data.taskNo;
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        downloadtemp: function(type) {
            $.ajax({
                type: "post",
                dataType: "json",
                url: DI.queryModelAddress,
                success: function(data) {
                    if (data.retFlag == 1) {
                        if (type == 1) {
                            window.location.href = data.data.percentModelUrl;
                        } else {
                            window.location.href = data.data.commModelUrl;
                        }
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        importXls: function() {
            $("#popup_import").show();
            popCtrl.taskNo = mainCtrl.taskNo;
        },
        nextComm: function() {
            if ($(this).hasClass("dis")) return;
            mainCtrl.tabIdx = 1;
        },
        savePercent: function() {
            if ($(this).hasClass("dis") || $("#taskTable1 .u-ipt.err-ipt").length > 0) return;
            var percentData = [];
            var iptList = $("#taskTable1 tbody .edit-ipt input");
            var tablelist = taskTable1.table.sources;
            for (var i = 0; i < tablelist.length; i++) {
                var percentObj = tablelist[i].$model.Id + "," + tablelist[i].$model.regionCode + "," + $(iptList[i]).val()
                percentData.push(percentObj);
            }
            var stringPercent = JSON.stringify(percentData);
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "percentList": stringPercent,
                    "taskNo": mainCtrl.taskNo
                },
                url: DI.updateRegionPercent,
                success: function(data) {
                    if (data.retFlag == 1) {
                        PLATFORM.showTips("success", "目标占比保存成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        prevPercent: function() {
            mainCtrl.tabIdx = 0;
        },
        saveComm: function() {
            if ($(this).hasClass("dis") || $("#taskTable2 .edit-ipt .err-ipt").length > 0) return;

            var commData = [];
            var iptList = $("#taskTable2 tbody .edit-ipt input");
            var tablelist = taskTable2.table.sources;
            for (var i = 0; i < tablelist.length; i++) {
                var commObj = tablelist[i].$model.commClassifyCode + "," + $(iptList[i]).val();
                commData.push(commObj);
            }
            var stringComm = JSON.stringify(commData);
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "commList": stringComm,
                    "taskNo": mainCtrl.taskNo
                },
                url: DI.updateCommNum,
                success: function(data) {
                    if (data.retFlag == 1) {
                        PLATFORM.showTips("success", "主推商品目标台数保存成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }
    });
    var opts = {
        targetId: "taskTable1",
        templateId: "tabletask1",
        settings: {
            searchParam: {
                "taskNo": mainCtrl.taskNo
            },
            url: DI.queryPercent,
            ajaxType: "json",
            sourceInterface: {
                INum: " ",
                IData: "data"
            },
            paginationIndexName: {
                "peerpageRows": "",
                "currentPage": ""
            }
        },
        customFuncs: {
            checkNumPoint: function() {
                $(this).removeClass("err-ipt").removeAttr("title");
                var reg = /^[0-9]+([.]{1}[0-9]{0,2})?$/;
                if (!reg.test($(this).val()) || $(this).val() == 0 || $(this).val() > 100) {
                    $(this).addClass("err-ipt").attr("title", "目标占比在0~100之间，最多精确到小数点后2位");
                }
            }
        }
    };
    var opts2 = {
        targetId: "taskTable2",
        templateId: "tabletask2",
        settings: {
            searchParam: {
                "taskNo": mainCtrl.taskNo
            },
            url: DI.queryCommList,
            ajaxType: "json",
            sourceInterface: {
                INum: "totalSize",
                IData: "records"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            }
        },
        customFuncs: {
            distributionInfo: function(commClassifyCode) {
                $("#popup_distribution").show();
                $("#load-assign").show();
                popCtrl.assignList = [];
                popCtrl.searchcode = "";
                $(".search-code .err-box").hide();
                location.hash = "popup_distribution";
                popCtrl.commClassifyCode = commClassifyCode;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    data: {
                        "commClassifyCode": commClassifyCode,
                        "taskNo": mainCtrl.taskNo
                    },
                    url: DI.queryAssign,
                    success: function(data) {
                        $("#load-assign").hide();
                        if (data.retFlag == 1) {
                            popCtrl.assignList = data.data;
                            var total = 0;
                            for (var i = 0; i < popCtrl.assignList.length; i++) {
                                var iptVal = popCtrl.assignList[i].destNum == undefined ? 0 : popCtrl.assignList[i].destNum;
                                total += parseInt(iptVal == "" ? 0 : iptVal, 10);
                            }
                            popCtrl.alldestnum = total;
                        } else {
                            console.log("获取分配详情接口，返回数据错误")
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            },
            delPop: function(row) {
                popCtrl.delId = row.commClassifyCode;
                popCtrl.delcommName = row.commName;
                $("#popup_del").show();
            },
            checkNum: function() {
                $(this).removeClass("err-ipt").removeAttr("title");
                var reg = /^[0-9]+$/;
                if (!reg.test($(this).val())) {
                    $(this).addClass("err-ipt").attr("title", "目标台数为数字");
                }
            }
        }
    };
    var popCtrl = avalon.define({
        $id: "popController",
        assignList: [],
        searchcode: "",
        delId: "",
        delcommName: "",
        taskNo: "",
        commClassifyCode: "",
        alldestnum: 0,
        uploadFile: function() {
            if ($("#upladFile").val() == "") {
                return;
            }
            $("#load-import").show();
            $("#form_file").ajaxSubmit({
                type: "post",
                dataType: "json",
                url: mainCtrl.tabIdx == 0 ? DI.importPercentFile : DI.importCommFile,
                success: function(data) {
                    $("#load-import").hide();
                    if (data.retFlag == 1) {
                        $("#popup_import").hide();
                        if (mainCtrl.tabIdx == 0) {
                            mainCtrl.isimppercent = true;
                            if (taskTable1 == null) {
                                opts.settings.searchParam.taskNo = mainCtrl.taskNo;
                                taskTable1 = SwiftUI.swiftTable.getInstance(opts);
                            } else {
                                taskTable1.searchParam.pageNo = "1";
                                taskTable1.refresh();
                            }

                        } else {
                            mainCtrl.isimpcomm = true;
                            if (taskTable2 == null) {
                                opts2.settings.searchParam.taskNo = mainCtrl.taskNo;
                                taskTable2 = SwiftUI.swiftTable.getInstance(opts2);
                            } else {
                                taskTable2.searchParam.pageNo = "1";
                                taskTable2.refresh();
                            }
                        }
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                    $("#upladFile").after($("#upladFile").clone().val(""));
                    $("#upladFile").remove();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("ajax error");
                    console.log(XMLHttpRequest);
                }
            });
        },
        fastSearch: function() {
            var codeList = $("#popup_distribution tbody tr .region-code");
            $(".region-code.highlight").removeClass("highlight");
            $(".search-code .err-box").hide();
            if(popCtrl.searchcode.length != 5){
                $(".search-code .err-box").show();
                return;
            }
            var hashId = "";
            for (var i = 0; i < popCtrl.assignList.length; i++) {
                if (popCtrl.assignList[i].orgCode.indexOf(popCtrl.searchcode) != -1) {
                    $(codeList[i]).addClass("highlight");
                    if (hashId == "") {
                        hashId = "td_" + popCtrl.assignList[i].orgCode;
                    }
                }
            }
            location.hash = "";
            location.hash = hashId;
        },
        saveRegionComm: function() {
            if ($("#popup_distribution .edit-ipt .err-ipt").length > 0) return;

            var commData = [];
            var iptList = $("#popup_distribution tbody .edit-ipt input");
            for (var i = 0; i < iptList.length; i++) {
                var commObj = (popCtrl.assignList[i].Id == undefined ? "" : popCtrl.assignList[i].Id) + "," + popCtrl.assignList[i].regionCode + "," + popCtrl.assignList[i].regionTaskNo + "," + $(iptList[i]).val();
                commData.push(commObj);
            }
            var stringComm = JSON.stringify(commData);
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "commList": stringComm,
                    "commClassifyCode": popCtrl.commClassifyCode,
                    "destNumHq": popCtrl.alldestnum
                },
                url: DI.updateRegionComm,
                success: function(data) {
                    if (data.retFlag == 1) {
                        taskTable2.searchParam.pageNo = "1";
                        taskTable2.refresh();
                        $("#popup_distribution").hide();
                        PLATFORM.showTips("success", "大区目标台数保存成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        delData: function() {
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "commClassifyCode": popCtrl.delId,
                    "commName": popCtrl.delcommName
                },
                url: DI.deleteComm,
                success: function(data) {
                    $("#popup_del").hide();
                    if (data.retFlag == 1) {
                        PLATFORM.showTips("success", "删除主推商品成功");
                        taskTable2.searchParam.pageNo = "1";
                        taskTable2.refresh();
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        checkNum: function() {
            $(this).removeClass("err-ipt").removeAttr("title");
            if ($(this).val() == "") {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    total += parseInt(iptVal, 10);
                }
                popCtrl.alldestnum = total;
                return;
            }
            var reg = /^[0-9]+$/;
            if (!reg.test($(this).val())) {
                $(this).addClass("err-ipt").attr("title", "目标台数为数字");
            } else {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    total += parseInt(iptVal, 10);
                }
                popCtrl.alldestnum = total;
            }
        }
    });
    $.ajax({
        type: "post",
        dataType: "json",
        url: DI.queryCategory,
        success: function(data) {
            if (data.retFlag == 1) {
                mainCtrl.categoryList = data.data;
            }
        },
        error: function(err) {
            console.log(err);
        }
    });

    PLATFORM.datepickerRangelimit("#starttime", 1, "#endtime");

    avalon.scan();
});
/*
 * firefox下回车事件不兼容问题
 * 
 */
function fastSearch(evt){
    evt = (evt) ? evt : ((window.event) ? window.event : "");  //兼容IE和Firefox获得keyBoardEvent对象
    var keyVal = evt.keyCode?evt.keyCode:evt.which;
    $(".search-code .u-ipt").val($(".search-code .u-ipt").val().replace(/\D/g,''));
    var searchCode = $(".search-code .u-ipt").val();
    if(keyVal == 13){
        var codeList = $("#popup_distribution tbody tr .region-code");
        $(".region-code.highlight").removeClass("highlight");
        $(".search-code .err-box").hide();
        if(searchCode.length != 5){
            $(".search-code .err-box").show();
            return;
        }
        var hashId = "";
        var tableList = $("#popup_distribution tbody tr"),
            tableLen = tableList.length;
        for (var i = 0; i < tableLen; i++) {
            var curCodeObj = $(tableList[i]).find(".region-code"),
                curCode = curCodeObj.text();
            console.log(curCode);
            if (curCode.indexOf(searchCode) != -1) {
                curCodeObj.find("span").addClass("highlight");
                if (hashId == "") {
                    hashId = "td_" + curCode;
                }
            }
        }
        location.hash = "";
        location.hash = hashId;
    }
}